/**
 * Created by TRwin7SP1 on 2016/7/28.
 */

if (typeof lmViewer === 'undefined') {
  lmViewer = {

    data: {
      flag:false,//series flag
      imageInfo: null,
      curCheckCode: '', // check code
      imageIDs: [], // this contains all image id, is is the image url
      series: [], // contain the series information
      seriesArray: [], // Contain series and isntances information
      tags: [],
      loaded: [], // Is the image loaded
      multiSeries: [], // is multi series
      loadedIndex: [], // Indicate each window loaded series
      clickedSeries: -1,
      rangeMin: 0, // for input range
      rangeMax: 0,
      synchronizer: null,
      // reportFlag : '',
      sort: 0,
      // image2askid : '',
      iWindowVNum: 1,
      iWindowHNum: 1,
      //patId : 0,
      //studyUID : 0,
      //imageType : "jpg",
      totalSeries: 0,
      isMobile: false,
      isDesktop: true,
      //askId : '',
      //imageId : null,
      imageInfo: null,
      studyNumber: 0, // Total studyNumber in this ask
      countser: 0,
      groupIndex: [],
      iSeriesNum: 0, // total series number 序列的长度
      locations: [], // each series location
      thickness: [], // each series thickness
      groupNum: 0, // the number of the groups, in each of which the series are synchronizers
      orientation: [], // each series orientation
      firwidth: 0,
      changgeSeriesByIndex: -1,
      synchronizers: [],
      synchrSwitch: false,
      viewportNum: 0, // total viewport number
      dis: true,
      maxSeriesNum: 0, // the maximum of "numberOfInstances" in every series
      wheelInstanceNum: [], // used to display the current instance number according to mouse wheel
      elementChoosed: '', // current element in canvas which is clicked
      initialWW: [], // initial window width of every instance
      initialWL: [], // initial window level of every instance
      globalWW: 0, // on mobile, when the window width of current image is modified, it is saved in "globalWW"
      globalWL: 0, // on mobile, when the window center of current image is modified, it is saved in "globalWL"
      contrastButtonPressed: false, // to judge whether the "enableWindowLevelTool" button has been pressed
      referenceLineButtonPressed: false, // to judge whether the "referenceLine" button has been pressed
      getDicomButtonPressed: false, // to judge whether the "getDicom" button has been pressed
      curImageID: '', // currrent image id
      curCheckCode: '', // check code
      isloaded: 0,
      eformid: null,
      tagArray: [],  // contain instances tags
      // queryString :window.location.href,
      //从咨询界面获取到的链接数据
      // queryString :"http://123.56.201.253/#/doctorMain/ddetailMessage?patientID=LOCAL_339&studyUID=1.2.156.112572.18161010101313.438782901.370&imageid=85&askId=391&image2askid=423&askType=1&reportFlag=1&type=jpg&a",
      //从我的影像列表获取到的链接数据
      queryString: "http://139.217.23.117/#/viewer?imageid=13&patientID=282024&studyUID=1.3.6.1.4.1.2452.6.2979096217.1111427281.2551271845.581268577&reportFlag=0&type=jpg",
      curImageNum: 0,
      queryParams: {
        patId: 0,
        studyUID: 0,
        imageType: '',
        reportFlag: '',
        image2askid: '',
        isSReport: '',
        askId: '',
        imageId: null,
        shareid: null,
        eformid: null,
        dcmurl: null,
        serverURL: null,
        hosturl: lm.environment().imageCloudPort,
      },
      autoPlayButtonPressed: true,
      isFirst: true,//用于左侧框收缩时判断是否为第一次
      windowWidth: document.documentElement.clientWidth,// document.body.clientWidth,//dom的宽度
      // windowWidth :document.body.clientWidth,//dom的宽度
      windowHeight: document.documentElement.clientHeight,//document.body.clientHeight,//dom高度
      isGetDicomButtonPressed: false,//判断是不是按的getDicom
      isShowSeriesByIndexPressed: false,
      isGridPressed: false,
      isToggle: false,
      count: 0,
      imageId: null,
      curSeriesId:null,//当前序列id
      RT:{
        isImageLoaded:false,
        imageLinesData:[],//保存已加载序列的实例的勾靶信息
        imageLines:[],//保存已选择的checkbox信息
        isContour:false
      },
      //todo tangzhengxiong 2016/9/26  当前活动窗口的影像的信息
      currentStatus:{
        series:{},
        instance:{},
        tag:{}
      }

    },
    fn: {

      RT:{

        showImageLines : function () {
          if(!lmViewer.data.RT.isContour)
            return;
          //清空线条
          lmViewer.fn.RT.removeToolState();

          var linesData = [];
          var imageLines = lmViewer.data.RT.imageLines;
          var imageLinesData = lmViewer.data.RT.imageLinesData;
          var toolType = "freehand";
          var element = $('#image00').get(0);

          for(var n=0;n<imageLines.length;n++) {

            for(var i=0;i<imageLinesData.length;i++){

              if(imageLinesData[i].seriesIUID === lmViewer.data.curSeriesId){

                var _instance = imageLinesData[i].instance;

                for(var instanceIndex =0 ;instanceIndex <_instance.length;instanceIndex++){

                  if(imageLines[n].fileName == _instance[instanceIndex].fileName)
                  {
                    var _linesData = _instance[instanceIndex].data;
                    for(var _dataIndex=0;_dataIndex<_linesData.length;_dataIndex++){

                       if(_linesData[_dataIndex].referringSOPInstanceUID === lmViewer.data.seriesArray[lmViewer.data.changgeSeriesByIndex].instance[lmViewer.data.curImageNum].sopIUID+''){
                         _linesData[_dataIndex].color = imageLines[n].color;
                         // linesData.push(_linesData[_dataIndex]);
                         _linesData[_dataIndex].tag = lmViewer.data.currentStatus.tag;
                         cornerstoneTools.addToolState(element, toolType, _linesData[_dataIndex]);
                       }
                    }
                  }

                }

              }
            }
          }
          cornerstone.updateImage(element);
        },

        renderStroke : function (Contour) {
          var element = $('#image00').get(0);
          cornerstoneTools.freehand.addLinesData(element,Contour);



        /*  var element = $('#image00').get(0);
         cornerstone.updateImage($('#image00').get(0));
          var cxt = $('#image00>canvas')[0].getContext('2d');
          // cxt.translate(300,200);
          cxt.lineWidth = 2.0;
          if (Contour === undefined) {
            return;
          }

          var TempAlpha =  cxt.globalAlpha;
          for (var i = 0; i < Contour.length; i++) {
            var line = Contour[i];
            // cxt.fillStyle = "rgb("+line.color+")";//填充绘画的颜色
            cxt.strokeStyle =line.color;
            cxt.globalAlpha = line.opacity || 0.5;

            // cxt.setTransform(1, 0, 0, 1, 0, 0);
            cxt.save();//保存现场
            cxt.beginPath();
            var offset_x = null;
            var offset_y = null;

            //获取当前图像的imagePosition
            var instanceInfo = lmViewer.data.tags.message;
            var imagePosition = null;
            var pixelSpacing = null;
            var imageOrientation = null;
            var rows = null,columns=null;
            var translateX = 0,translateY=0;
            for(var index = 0;index<instanceInfo.length;index++){
              if(instanceInfo[index].seriesIuid == lmViewer.data.curSeriesId && instanceInfo[index].sopIuid == line.referringSOPInstanceUID){
                imagePosition = instanceInfo[index].imagePosition.split('\\');
                pixelSpacing =  instanceInfo[index].pixelSpacing.split('\\');
                imageOrientation =  instanceInfo[index].imageOrientation.split('\\');
                rows = instanceInfo[index].rows;
                columns = instanceInfo[index].columns;
              }
            }
            var totalWidth = $('#image00>canvas').width();
            var totalHeight = $('#image00>canvas').height();

            offset_x = (totalWidth-rows)/2;
            offset_y = (totalHeight-columns)/2;

            /!**获取影像的偏移
             *
             * 当影像未知发生变化时，线条位置变化
             * translation:影像向上向左移动为负，向下向右移动为正
             *!/
            var scale=null;
            var viewport = cornerstone.getEnabledElement(element).viewport;
            if(viewport && viewport.translation){
              scale = viewport.scale;
              cxt.scale(scale,scale);

              offset_x += viewport.translation.x * scale;
              offset_y += viewport.translation.y * scale;

            }


            for (var j = 0; j < line.handles.length; j++) {
              var point = line.handles[j];
              if (0 === j) {
                cxt.moveTo(lmViewer.fn.RT.calculatePosition(point.x,imagePosition[0],pixelSpacing[0])+offset_x,
                          lmViewer.fn.RT.calculatePosition(point.y,imagePosition[1],pixelSpacing[1])+offset_y);
              } else {
                cxt.lineTo(lmViewer.fn.RT.calculatePosition(point.x,imagePosition[0],pixelSpacing[0])+offset_x,
                          lmViewer.fn.RT.calculatePosition(point.y,imagePosition[1],pixelSpacing[1])+offset_y);
              }
            }

            cxt.closePath();
            // cxt.fill();
            cxt.stroke();
            cxt.restore();//恢复现场
          }
          cxt.globalAlpha = TempAlpha;*/

        },

        scrollFunc:function(){
          var cxt = $('#image00>canvas')[0].getContext('2d');
          cxt.strokeStyle = "white";//笔触的颜色、渐变或模式
          cxt.globalAlpha = 1.0;
          cxt.lineWidth = 0.3;

          // var linesData = lmViewer.data.RT.imageLinesData[0].instance;
          //绘制线条
          lmViewer.fn.RT.renderStroke(cxt,linesData);
         },

        getContourData:function(obj){

          /*          for(var m=0;m<lmViewer.data.RT.imageLinesData.length;m++){
                      if(lmViewer.data.RT.imageLinesData.seriesIUID == lmViewer.data.RT.curSeriesId){
                        // for(var m=0;m<)
                      }
                      // for(var n=0;n<)
                    };*/
          /*          var url ='http://192.168.100.113:9000/api/structure/ROIPlane/'+obj;
          $.get(url,function(data){
            var _transArray = lmViewer.fn.RT.getToolData(data);
            var _lineData = {
              fileName:obj,
              seriesIUID:lmViewer.data.RT.curSeriesId,
              instance:_transArray
            };
            console.log(_transArray);
            lmViewer.data.RT.imageLinesData.push(_lineData);
            lmViewer.fn.RT.showImageLines();
          });*/

          var url =lm.environment("RTlocalserver").hostUrl+'/api/structure/ROIPlane/'+obj;
          $.get(url,function(data){
            var _transArray = lmViewer.fn.RT.getToolData(data);
            var _linesData = {
              seriesIUID:lmViewer.data.curSeriesId,
              instance:[]
            };
            var _instance ={
              fileName:obj,
              data:_transArray.data
            }
            _linesData.instance.push(_instance);
            lmViewer.data.RT.imageLinesData.push(_linesData);
            lmViewer.fn.RT.showImageLines();
          });
        },

        getToolData:function(array){

          var _DataArray= lmViewer.fn.RT.tranlateArray(array);
          //保存所有的线
          var _TempArray = {
            data:[]
          };

          for(var index=0;index<_DataArray.length;index++){
            //偏移
            var  _offset ={
              x:100,
              y:100,
              z:100,
            }
            //一条线
            var _line = {
              "visible": true,
              "active": false,
              "offset":_DataArray[index].original || _offset,
              "color": _DataArray[index].color || 'white',
              "handles": [],
              // "seriesIUID":"1.2.156.112572.18161010101313.5325155543.6",//序列ID
              //"instanceNumber":0 //实例的num
              "referringSOPInstanceUID": _DataArray[index].referringSOPInstanceUID,
              "contourGeometricType": _DataArray[index].contourGeometricType,
              "numofContourPoints": _DataArray[index].numofContourPoints,
              "tag":{}
            };
            //设置点
            var _handles = [];
            var _length = _DataArray[index].contourData.length;
            for(var i=0;i<_length;i++){
              //点
              var _Point = {
                "x": 0,
                "y":0,
                "z":0,
                "highlight": true,
                "active": true,
                "lines": [
                  {
                    "x":0,
                    "y":0,
                    "z":0,
                  }
                ]
              };
              //起始点
              var _value = _DataArray[index].contourData;
              _Point.x=_value[i][0];
              _Point.y=_value[i][1];
              _Point.z=_value[i][2];
              //结束点
              if(i===_length-1){
                _Point.lines[0].x=_value[0][0];
                _Point.lines[0].y=_value[0][1];
                _Point.lines[0].z=_value[0][2];
              }else{
                _Point.lines[0].x=_value[i+1][0];
                _Point.lines[0].y=_value[i+1][1];
                _Point.lines[0].z=_value[i+1][2];
              }
              //
              _handles.push(_Point);
            }
            _line.handles = _handles;
            _TempArray.data.push(_line);
          }
          return _TempArray;
        },

        tranlateArray:function (array){
          for(var n=0;n<array.length;n++){
            var _message = array[n].contourData;
            var _result = [];
            var _length = _message.length;

            for(var i=0;i<_length/3;i++){
              var _obj = [];
              for(var j=i*3;j<(i+1)*3;j++){
                _obj.push(_message[j]);
              }
              _result.push(_obj);
            }
            array[n].contourData = _result;
          }
          //返回新的数组
          return array;
        },
        //设置影像缩放

        setScale : function(element,image){
          var viewport = cornerstone.getEnabledElement(element).viewport;
          viewport.scale = 1.0;
          cornerstone.setViewport(element, viewport);





/*          var enabledElement = cornerstone.getEnabledElement(element);
          var viewport = enabledElement.viewport;
          if(viewport === undefined) {
            viewport = cornerstone.internal.getDefaultViewport(enabledElement.canvas, image);
            viewport.scale = 1.0;
            cornerstone.setViewport(element, viewport);
          }*/
        },

        calculatePosition : function(line,imagePosition,pixelSpacing){
          var position = (line-imagePosition)/pixelSpacing;
          return position;
        },

        setCurrentTag:function(){
          if(!lmViewer.data.tags && lmViewer.data.tags.message.length===0){
            return;
          }
          for(var i=0;i<lmViewer.data.tags.message.length;i++){
            if(lmViewer.data.tags.message[i].seriesIuid == lmViewer.data.currentStatus.series.seriesIUID &&　lmViewer.data.tags.message[i].sopIuid==lmViewer.data.currentStatus.instance.sopIUID){
              lmViewer.data.currentStatus.tag = lmViewer.data.tags.message[i];
            }
          }
        },

        removeToolState:function(){
          var toolType = "freehand";
          var element = $('#image00').get(0);

          cornerstoneTools.clearToolState(element,toolType);

        }
        },


      circulation: new Function(),

      /*
      *
      * 设置Querystring字符串
      * */
      setQueryString: function (path) {
        lmViewer.data.queryString= path;
      },
      /*
       * 解析使用get方式调用阅片模块数据
       *
       * */
      parseQueryString: function () {

        var _params = lmViewer.data.queryParams;
        var _obj = {
          patId: lmViewer.fn.getParameter(lmViewer.data.queryString, "patientID"),
          studyUID: lmViewer.fn.getParameter(lmViewer.data.queryString, "studyUID"),
          imageType: lmViewer.fn.getParameter(lmViewer.data.queryString, "type"),
          reportFlag: lmViewer.fn.getParameter(lmViewer.data.queryString, "reportFlag"),
          image2askid: lmViewer.fn.getParameter(lmViewer.data.queryString, "image2askid"),
          isSReport: lmViewer.fn.getParameter(lmViewer.data.queryString, "sReport"),
          askId: lmViewer.fn.getParameter(lmViewer.data.queryString, "askid"),
          imageId: lmViewer.fn.getParameter(lmViewer.data.queryString, "imageid"),
          shareid: lmViewer.fn.getParameter(lmViewer.data.queryString, "shareid"),
          eformid: lmViewer.fn.getParameter(lmViewer.data.queryString, "eformid"),
          /*                    dcmurl:lmViewer.data.queryParams.dcmurl,
           serverURL : lmViewer.data.queryParams.serverURL,
           hosturl : lm.environment().imageCloudPort,*/
        };
        lmViewer.data.queryParams = _obj;
        lmViewer.data.queryParams.hosturl = lm.environment().imageCloudPort;
        return true;
      },

      getStudyNumber: function () {
        //获得检查数量
        if (lmViewer.data.queryParams.askId == null) {
          return;
        }
        var _data = {};
        _data.askid = lmViewer.data.queryParams.askId;
        _data.curpage = 1;
        _data.pagesize = 5;

        lmViewer.srv.service_ask_imagelist(_data, function (data) {
//                    console.log("[tabViewer|service_ask_imagelist|success]---"+JSON.stringify(data,null,4));
          var result = data.result;
          if (result == 0) {
            var message = data.message;
            if (message) {
              lmViewer.data.sstudyNumber = message.length;
            }
          } else if (result == -1) {
            humane.log("获取影像数据失败");
          } else {
            humane.log("未知错误");
          }
        }, function (data) {
          humane.log("服务器异常");
        });
      },

      sortTagSeries: function () {
        //序列对象排序
        var tempTagArray = [];
        var sNum = lmViewer.data.series.length;

        // 将tagArray与seriesArray的序列顺序统一,之前seriesArray曾用此法与series统一过
        for (var i = 0; i < sNum; i++) {
          for (var j = 0; j < sNum; j++) {
            if (lmViewer.data.series[i].seriesIUID == lmViewer.data.seriesArray[j].seriesUID) {
              tempTagArray.push(lmViewer.data.tagArray[j]);
              break;
            }
          }
        }
        lmViewer.data.tagArray = tempTagArray;

        //将tagArray与seriesArray每个序列的instance顺序统一
        for (var i = 0; i < sNum; i++) {
          var tempInstances = [];
          var iNum = lmViewer.data.seriesArray[i].instance.length;

          for (var se = 0; se < iNum; se++) {
            for (var tag = 0; tag < iNum; tag++) {
              if (lmViewer.data.seriesArray[i].instance[se].sopIUID == lmViewer.data.tagArray[i][tag].instanceId) {
                tempInstances.push(lmViewer.data.tagArray[i][tag]);
                break;
              }
            }
          }
          lmViewer.data.tagArray[i] = tempInstances;
        }
      },

      loadInstances: function (obj) {

        var _params = lmViewer.data.queryParams;
        var _data = {
          hostURL: _params.hosturl,
          patientid: _params.patId,
          studyid: _params.studyUID,
          seriesid: obj.seriesUID,
          dcmURL: _params.dcmurl,
          serverURL: _params.serverURL
        };
        lmViewer.srv.service_instances_getinstances(_data, function (data) {

                  // console.log("[imageShow|service_instances_getinstances|success]---"+JSON.stringify(data,null,4));
          var instances = data.message;
          var objmo = new Object();
          var ob = {
            seriesUID: obj.seriesUID,
            instance: instances
          };

          lmViewer.data.locations[obj.index] = instances[0].sliceLocation;
          lmViewer.data.thickness[obj.index] = instances[0].sliceThickness;
          lmViewer.data.orientation[obj.index] = instances[0].imgOrient;

          // Save series
          lmViewer.data.seriesArray.push(ob);
          lmViewer.data.loaded.push(1);
          lmViewer.data.loadedIndex.push(-1);
          //todo tangzhengxiong 2016/9/19
          lmViewer.data.curImageNum = instances[0].instanceNumber;
          //todo tangzhengxiong 2016/9/26
          lmViewer.data.currentStatus.instance = instances[0];
/*          //todo tangzhengxiong 2016/9/26
          lmViewer.data.currentStatus.tag = data;*/

          lmViewer.fn.RT.setCurrentTag();

          var instanceImgs = ob.instance;
          var instanceLength = ob.instance.length;

          for (var i = 0; i < instanceLength; i++) {
            var tagElement = new Object();
            lmViewer.data.tagArray[obj.index].push(tagElement);
          };

          lmViewer.ctrl.initDicomViewer();
        }, function (data) {
          humane.log(
            "影像服务器连接错误。Cannot connect server to get the series information.",
            {
              timeout: 4000,
              clickToClose: true,
              addnCls: 'humane-error'
            });
        });
      },

      loadTagInfos: function () {
        // load the tags of all the instances in the current study
        var _data = {
          studyIuid: lmViewer.data.queryParams.studyUID
        };
        lmViewer.srv.GetFileMetaInfoServlet(_data, function (data) {
//                   console.log("[imageShow|GetFileMetaInfoServlet|success]---"+JSON.stringify(data,null,4));
          lmViewer.data.tags = data;
        });
      },

      getParameter: function (queryString, parameterName) {
        // load the parameter from querystring
        // Add "=" to the parameter name (i.e. parameterName=value);
        var parameterName = parameterName + "=";
        if (queryString.length > 0) {
          // Find the beginning of the string
          var begin = queryString.indexOf(parameterName);
          if (begin != -1) {
            // Add the length (integer) to the beginning
            begin += parameterName.length;
            var end = queryString.indexOf("&", begin);
            if (end == -1) {
              end = queryString.length;
            }
            return unescape(queryString.substring(begin, end));
          }
          return null;
        }
      },

      // loadImages:function(hosturl, serverURL, studyUID, series, imagesid, type) {
      loadImages: function (obj) {
        // 影像全路径（通过该路径下载影响）
        var insNum = obj.series.instance.length;
        var _params = lmViewer.data.queryParams;
        //todo tangzhengxiong 2016/9/18
        lmViewer.data.curImageNum = obj.series.instance[0].instanceNumber;

        if (_params.imageType == "" || _params.imageType == null) {
          for (var i = 0; i < insNum; i++) {
            var imageURL = "";

            if (_params.imageType == "dicom" || _params.imageType == "dicom#") {
              imageURL = imageURL + "dicomweb:" + _params.hosturl + '/imagecloud/read?'
                + 'serverURL=' + _params.serverURL + '/wado&' + 'study='
                + _params.studyUID + '&series=' + obj.series.seriesUID + '&object='
                + obj.series.instance[i].sopIUID
                + '&contentType=application%2Fdicom';
            }
            else if (_params.imageType == "png" || _params.imageType == "png#") {
              imageURL = imageURL + _params.hosturl + '/imagecloud/read?' + 'serverURL='
                + _params.serverURL + '/wado&' + 'study=' + _params.studyUID
                + '&series=' + obj.series.seriesUID + '&object='
                + obj.series.instance[i].sopIUID + '&contentType=image/png';
            }
            else {
              imageURL = imageURL + _params.hosturl + '/imagecloud/read?' + 'serverURL='
                + _params.serverURL + '/wado&study=' + _params.studyUID
                + '&series=' + obj.series.seriesUID + '&object='
                + obj.series.instance[i].sopIUID;
            }
            obj.imagesid.push(imageURL);
          }
        } else {
          for (var i = 0; i < insNum; i++) {
            var imageURL = "";

            if (_params.imageType == "dicom" || _params.imageType == "dicom#") {
              imageURL = imageURL + "dicomweb:" + _params.hosturl + '/imagecloud/read?'
                + 'serverURL=' + _params.serverURL + '/wado&' + 'study='
                + _params.studyUID + '&series=' + obj.series.seriesUID + '&object='
                + obj.series.instance[i].sopIUID + '&rows=512'
                + '&contentType=application%2Fdicom';
            } else if (_params.imageType == "jpg" || _params.imageType == "jpg#") {
              imageURL = imageURL + _params.hosturl + '/imagecloud/read?' + 'serverURL='
                + _params.serverURL + '/wado&' + 'study=' + _params.studyUID
                + '&series=' + obj.series.seriesUID + '&object='
                + obj.series.instance[i].sopIUID + '&rows=512';
            } else if (_params.imageType == "png" || _params.imageType == "png#") {
              imageURL = imageURL + _params.hosturl + '/imagecloud/read?' + 'serverURL='
                + _params.serverURL + '/wado&' + 'study=' + _params.studyUID
                + '&series=' + obj.series.seriesUID + '&object='
                + obj.series.instance[i].sopIUID + '&rows=512'
                + '&contentType=image/png';

            }

            obj.imagesid.push(imageURL);
          }
        }
      },

      sortSeries: function () {
        // 序列对象排序
        var tempSeriesArray = [];
        //	var tempTagArray = [];
        var sNum = lmViewer.data.series.length;
        for (var i = 0; i < sNum; i++) {

          // find proper seriesID
          var poperIndex = '';
          for (var j = 0; j < sNum; j++) {
            if (lmViewer.data.series[i].seriesIUID == lmViewer.data.seriesArray[j].seriesUID) {
              tempSeriesArray.push(lmViewer.data.seriesArray[j]);
              //	tempTagArray.push(tagArray[j]);
              break;
            }
          }
        }
        lmViewer.data.seriesArray = tempSeriesArray;
        //	tagArray = tempTagArray;
      },

      triggerResize: function () {
        // is loaded completely
        var itotal = 0;
        for (var i = 0; i < lmViewer.data.multiSeries.length; i++) {
          itotal = itotal + lmViewer.data.multiSeries[i];
        }
        if (itotal == lmViewer.data.iWindowVNum * lmViewer.data.iWindowHNum || itotal == lmViewer.data.totalSeries) {
          // if (lmViewer.data.queryParams.shareid != null) {
          //   lmViewer.ui.resizeCanvas_share();
          // } else {
            lmViewer.ui.resizeCanvas();
          // }
          lmViewer.ui.resizeSeriesDiv();
        }
      },

      getDicom: function (obj) {
        //used to get the dicom image of the current jpg ------------------------------ Updated by TanQilu

        var eElement = cornerstone.getEnabledElement(obj.element);
        if (eElement.image.imageId.indexOf("dicomweb") == -1) {
          // convert current imageId to one from which you can achieve the dicom image
          eElement.image.imageId = 'dicomweb:' + eElement.image.imageId + '&contentType=application%2Fdicom';
        }
        return eElement.image.imageId;
      },

      selectImage: function (obj) {
        // 设置阅片下的进度条
        for (var x = 0; x < lmViewer.data.iWindowHNum; x++) {
          for (var y = 0; y < lmViewer.data.iWindowVNum; y++) {

            var imageDivId = "image" + x.toString() + y.toString();
            var element = $('#' + imageDivId).get(0);

            if (element === undefined) {
              continue;
            }

            // Get the range input value
            var newImageIdIndex = parseInt(obj.event.currentTarget.value, 10);

            // Get the stack data
            var stackToolDataSource = cornerstoneTools.getToolState(element,
              'stack');
            if (stackToolDataSource === undefined) {
              return;
            }
            var stackData = stackToolDataSource.data[0];

            // Switch images, if necessary
            if (newImageIdIndex !== stackData.currentImageIdIndex
              && stackData.imageIds[newImageIdIndex] !== undefined) {
              cornerstone.loadAndCacheImage(
                stackData.imageIds[newImageIdIndex]).then(
                function (image) {
                  var viewport = cornerstone.getViewport(element);
                  stackData.currentImageIdIndex = newImageIdIndex;
                  cornerstone.displayImage(element, image, viewport);
                });
            }

          }

        }

      },

      selectNewImage: function (obj) {

        for (var x = 0; x < lmViewer.data.iWindowHNum; x++) {
          for (var y = 0; y < lmViewer.data.iWindowVNum; y++) {

            var imageDivId = "image" + x.toString() + y.toString();
            var element = $('#' + imageDivId).get(0);

            if (element === undefined) {
              continue;
            }

            // Get the range input value
            var newImageIdIndex = parseInt(obj.newIndex, 10);

            // Get the stack data
            var stackToolDataSource = cornerstoneTools.getToolState(element,
              'stack');
            if (stackToolDataSource === undefined) {
              return;
            }
            var stackData = stackToolDataSource.data[0];

            // Switch images, if necessary
            if (newImageIdIndex !== stackData.currentImageIdIndex
              && stackData.imageIds[newImageIdIndex] !== undefined) {
              cornerstone.loadAndCacheImage(
                stackData.imageIds[newImageIdIndex]).then(
                function (image) {
                  var viewport = cornerstone.getViewport(element);
                  stackData.currentImageIdIndex = newImageIdIndex;
                  cornerstone.displayImage(element, image, viewport);
                });

            }
          }
        }
      },

      /* parseMessageData:function(data) {
       try {

       var message = JSON.parse(data);
       return message;
       } catch (e) {
       humane.log("解析数据出错");
       return false;
       }
       },*/

      distinguishGroup: function () {
        // Distinguish the gourp index for synchronize the viewers

        lmViewer.data.groupIndex[0] = 0;

        for (var i = 1; i < lmViewer.data.iSeriesNum; i++) {
          if (lmViewer.data.thickness[i] == lmViewer.data.thickness[0]
            && Math.abs(lmViewer.data.locations[i] - lmViewer.data.locations[0]) < 0.35
            && lmViewer.data.orientation[i] == lmViewer.data.orientation[0]) {
            lmViewer.data.groupIndex[i] = lmViewer.data.groupNum;
          } else {
            lmViewer.data.groupIndex[i] = lmViewer.data.groupNum + 1;
          }
        }

        lmViewer.data.groupNum++;

        for (var i = 1; i < lmViewer.data.iSeriesNum; i++) {
          if (lmViewer.data.groupIndex[i] == lmViewer.data.groupNum) {
            for (var j = i + 1; j < lmViewer.data.iSeriesNum; j++) {
              if (lmViewer.data.groupIndex[j] == lmViewer.data.groupNum) {
                if (lmViewer.data.thickness[i] == lmViewer.data.thickness[j]
                  && Math.abs(lmViewer.data.locations[i] - lmViewer.data.locations[j]) < 0.35
                  && lmViewer.data.orientation[i] == lmViewer.data.orientation[j]) {
                  lmViewer.data.groupIndex[j] = lmViewer.data.groupNum;
                } else {
                  lmViewer.data.groupIndex[j] = lmViewer.data.groupNum + 1;
                }
              }
            }
            lmViewer.data.groupNum++;
          }
        }
        lmViewer.data.groupNum--;

        var totalGroupNumber = 0;
        for (var i = 0; i < lmViewer.data.groupIndex.length; i++) {
          if (lmViewer.data.groupIndex[i] > totalGroupNumber) {
            totalGroupNumber = lmViewer.data.groupIndex[i] + 1;
          }
        }

        totalGroupNumber++;
        for (var i = 0; i < totalGroupNumber; i++) {
          lmViewer.data.synchronizers[i] = new cornerstoneTools.Synchronizer(
            "CornerstoneNewImage",
            cornerstoneTools.stackImageIndexSynchronizer);
        }
      },

      renumberInstances: function () {
        //renumber the instances of every series -----------------------------------Updated by TanQilu
        for (var i = 0; i < lmViewer.data.seriesArray.length; i++) {
          for (var j = 0; j < lmViewer.data.seriesArray[i].instance.length; j++) {
            lmViewer.data.seriesArray[i].instance[j].instanceNumber = j;
          }
        }
      },

      inverseMatrix: function (arr) {//正确
        //求矩阵的逆
        arrIS = new Array(arr.length);//最大元素的行号
        arrJS = new Array(arr.length);//最大元素的列号
        f = 1;
        fDet = 1;
        for (k = 0; k < arr.length; k++) {
          //第一步 -- 全选主元
          arrMax = 0;
          for (i = k; i < arr.length; i++) {
            for (j = k; j < arr.length; j++) {
              f = Math.abs(arr[i][j]);
              if (f > arrMax) {
                arrMax = f;
                arrIS[k] = i;
                arrJS[k] = j;
              }
            }
          }
          if (Math.abs(arrMax) < 0.000001)return arr;
          if (arrIS[k] != k) {
            f = -f;
            for (kk = 0; kk < arr.length; kk++) {
              temp = swap([arr[k][kk], arr[arrIS[k]][kk]]);
              arr[k][kk] = temp[0];
              arr[arrIS[k]][kk] = temp[1];
            }
          }
          if (arrJS[k] != k) {
            f = -f;
            for (kk = 0; kk < arr.length; kk++) {
              temp = swap([arr[kk][k], arr[kk][arrJS[k]]]);
              arr[kk][k] = temp[0];
              arr[kk][arrJS[k]] = temp[1];
            }
          }
          // 计算行列值
          fDet *= arr[k][k];
          // 计算逆矩阵
          arr[k][k] = 1 / arr[k][k];
          // 第三步
          for (j = 0; j < arr.length; j++) {
            if (j != k) arr[k][j] *= arr[k][k];
          }
          // 第四步
          for (i = 0; i < arr.length; i++) {
            if (i != k) {
              for (j = 0; j < arr.length; j++) {
                if (j != k) arr[i][j] = arr[i][j] - arr[i][k] * arr[k][j];
              }
            }
          }
          // 第五步
          for (i = 0; i < arr.length; i++) {
            if (i != k)arr[i][k] *= -arr[k][k];
          }
          //--end of k=0,..,n-1
        }
        //最后恢复
        for (k = arr.length - 1; k >= 0; k--) {
          if (arrJS[k] != k) {
            for (kk = 0; kk < arr.length; kk++) {
              temp = swap([arr[k][kk], arr[arrJS[k]][kk]]);
              arr[k][kk] = temp[0];
              arr[arrJS[k]][kk] = temp[1];
            }
          }
          if (arrIS[k] != k) {
            for (kk = 0; kk < arr.length; kk++) {
              temp = swap([arr[kk][k], arr[kk][arrIS[k]]]);
              arr[kk][k] = temp[0];
              arr[kk][arrIS[k]] = temp[1];
            }
          }
        }
        return arr;
      },

      // getImgIndex:function(element/*optional*/,image/*optional*/){
      getImgIndex: function (obj) {
        // get the series number and instance number of the element---------------- Updated by TanQilu
        var imgNum = '';
        var instanceNum = 0;
        var startIdx = 0;
        var endIdx = 0;
        var seriesId = '';
        var seriesNum = '';

        if (obj.element != undefined) {
          // find the instanceNum
          imgNum = obj.element.children[2].innerHTML.split('<br>')[0].split('：')[1];
          instanceNum = parseInt(imgNum.split('/')[0]) - 1;
          // find the seriesId
          startIdx = cornerstone.getImage(obj.element).imageId.indexOf('series') + 7;
          endIdx = cornerstone.getImage(obj.element).imageId.indexOf('&object');
          seriesId = cornerstone.getImage(obj.element).imageId.substring(startIdx, endIdx);
        }

        if (obj.image != undefined) {
          // find the seriesId
          startIdx = obj.image.imageId.indexOf('series') + 7;
          endIdx = obj.image.imageId.indexOf('&object');
          seriesId = obj.image.imageId.substring(startIdx, endIdx);
        }

        // find the seriesNum
        for (var i = 0; i < lmViewer.data.seriesArray.length; i++) {
          if (seriesId == lmViewer.data.seriesArray[i].seriesUID) {
            seriesNum = i;
            break;
          }
        }

        if (obj.image != undefined) {
          // find the instanceNum this image
          var idStart = obj.image.imageId.indexOf('object=') + 7;
          var idEnd = obj.image.imageId.indexOf('&rows');
          var objectId = obj.image.imageId.substring(idStart, idEnd);

          for (var i = 0; i < lmViewer.data.seriesArray[seriesNum].instance.length; i++) {
            if (objectId == lmViewer.data.seriesArray[seriesNum].instance[i].sopIUID) {
              instanceNum = i;
              break;
            }
          }
        }

        var imgIndex = {
          instance: instanceNum,
          series: seriesNum
        }
        return imgIndex;
      },

      sortTags: function () {
        // this function is used to sort the "tags" array, in order to unify the structure
        // of "tagArray" and "seriesArray" ---------------------------------- Updated by TanQilu

        // for each element in tags, judge the position in the "tagArray" it should be in
        for (var i = 0; i < lmViewer.data.tags.length; i++) {
          // to confirm the first index of the element (its series number)
          for (var j = 0; j < lmViewer.data.seriesArray.length; j++) {
            if (lmViewer.data.tags[i].seriesIuid == lmViewer.data.seriesArray[j].seriesUID) {
              // to confirm the second index of the element (its instance number)
              for (var k = 0; k < lmViewer.data.seriesArray[j].instance.length; k++) {
                if (lmViewer.data.tags[i].sopIuid == lmViewer.data.seriesArray[j].instance[k].sopIUID) {
                  lmViewer.data.tagArray[j][k] = lmViewer.data.tags[i];
                  j = lmViewer.data.seriesArray.length;
                  break;
                }
              }
            }
          }
        }
      },

      getDicom: function (obj) {
        //used to get the dicom image of the current jpg ------------------------------ Updated by TanQilu
        var eElement = cornerstone.getEnabledElement(obj.element);
        if (eElement.image.imageId.indexOf("dicomweb") == -1) {
          // convert current imageId to one from which you can achieve the dicom image
          eElement.image.imageId = 'dicomweb:' + eElement.image.imageId + '&contentType=application%2Fdicom';
        }
        return eElement.image.imageId;
      },

      achieveInstanceInfo: function () {
        var loc = [];
        var thick = [];
        var orient = [];
        var pos = [];

        var imageIDs = [];
        for (var i = 0; i < lmViewer.data.seriesArray.length; i++) {
          var _obj = {
            series: lmViewer.data.seriesArray[cnt],
            imagesid: imageIDs
          };
          lmViewer.fn.loadImages(_obj);
          for (var j = 0; j < lmViewer.data.seriesArray[i].instance.length; j++) {
            cornerstone.loadAndCacheImage(imageIDs[j]).then(function (image) {
              loc[j] = image.data.floatString('x00201041');
              thick[j] = image.data.floatString('x00180050');
              orient[j] = image.data.floatString('x00200037', 0).toString() + '/' +
                image.data.floatString('x00200037', 1).toString() + '/' +
                image.data.floatString('x00200037', 2).toString() + '/' +
                image.data.floatString('x00200037', 3).toString() + '/' +
                image.data.floatString('x00200037', 4).toString() + '/' +
                image.data.floatString('x00200037', 5).toString();
              pos[j] = image.data.floatString('x00200032', 0).toString() + '/' +
                image.data.floatString('x00200032', 1).toString() + '/' +
                image.data.floatString('x00200032', 1).toString();

            });//}(j);
            //   		loc[j] = seriesArray[i].instance[j].sliceLocation;
            //   		thick[j] = seriesArray[i].instance[j].sliceThickness;
            //   		orient[j] = seriesArray[i].instance[j].orientation;
            //   		pos[j] = seriesArray[i].instance[j].imgPosition;
          }
          lmViewer.data.locations.push(loc);
          lmViewer.data.thickness.push(thick);
          lmViewer.data.orientation.push(orient);
          lmViewer.data.position.push(pos);
          loc = [];
          thick = [];
          orient = [];
          pos = [];

          imageIDs = [];
        }
      },

      notifyConfigure: function () {
        humane.timeout = 4000;
        humane.addnCls = 'humane-libnotify-info';
      },

      plottingScale: function (obj) {
        try {
          // get the series number and instance number
          var _obj = {
            element: obj.element,
            image: undefined
          };
          var imgIndex = lmViewer.fn.getImgIndex(_obj);

          // get the series number and instance number
          var instanceNum = imgIndex.instance;
          var seriesNum = imgIndex.series;

          // achieve the image information
          //		var row = cornerstone.getImage(element).rows;
          //		var column = cornerstone.getImage(element).columns;
          var row = parseFloat(tagArray[seriesNum][instanceNum].rows);
          var column = parseFloat(tagArray[seriesNum][instanceNum].columns);

          var rowSpacing = parseFloat(tagArray[seriesNum][instanceNum].pixelSpacing.split('\\')[0]);
          var columnSpacing = parseFloat(tagArray[seriesNum][instanceNum].pixelSpacing.split('\\')[1]);
          //		var rowSpacing = cornerstone.getImage(element).rowPixelSpacing;
          //		var columnSpacing = cornerstone.getImage(element).columnPixelSpacing;

          // 如果是JPG格式，校准坐标系
          var rowScale = 1;
          var columnScale = 1;
          if (cornerstone.getImage(obj.element).data == undefined) { // JPG
            var jpgRow = cornerstone.getImage(obj.element).rows;
            var jpgColumn = cornerstone.getImage(obj.element).columns;
            rowScale = row / jpgRow;
            columnScale = column / jpgColumn;
          }

          // the width of the scale div
          var zoom = cornerstone.getEnabledElement(obj.element).viewport.scale;
          var len = column / columnScale * zoom;
          // the left margin of the scale div
          var viewportWidth = $('#' + obj.element.id).find('canvas').width();
          var sideMargin = parseInt((viewportWidth - len) / 2) > 0 ? parseInt((viewportWidth - len) / 2) : 0;

          $('#scaleDiv' + obj.element.id.substring(5)).remove();

          // scale div
          var scaleDiv = $('<div></div>');
          scaleDiv.attr('id', 'scaleDiv' + obj.element.id.substring(5));
          scaleDiv.attr('style', 'position: absolute; bottom: 6px; left:' + sideMargin + 'px; right:' + sideMargin + 'px; height: 40px;');
          scaleDiv.appendTo($('#' + obj.element.id));

          // scale canvas, in which we plot the scale
          var scale = $('<canvas></canvas>');
          scale.attr('id', 'scale' + obj.element.id.substring(5));
          scale.attr('width', (len + 40 < viewportWidth ? len + 40 : viewportWidth).toString() + 'px');
          scale.attr('height', '40px');
          scale.appendTo($('#scaleDiv' + obj.element.id.substring(5)));

          // plot the scale
          var canvas = document.getElementById('scale' + obj.element.id.substring(5));
          var context = canvas.getContext("2d");
          context.beginPath();
          context.lineWidth = 2;
          context.strokeStyle = 'white';
          context.moveTo(0, 40);
          context.lineTo(len - 1, 40);

          // define the text style written in the canvas
          cornerstoneTools.textStyle.setFont('12px Arial');
          var font = cornerstoneTools.textStyle.getFont();
          context.font = font;
          cornerstoneTools.drawTextBox(context, 'cm', len + 15, 40 - 5, 'white');

          // draw the scale marks
          var i = 0, time = 0;
          while (i < len) {
            context.moveTo(i, 40);
            context.lineTo(i, 40 - 5);

            cornerstoneTools.drawTextBox(context, (5 * time).toString(), i, 40 - 5, 'white');

            i += 50 / (columnSpacing * columnScale) * zoom;
            time++;
          }

          context.stroke();

          // 竖屏状态下调整底部的导航栏宽度
          if (lmViewer.data.isDesktop || lmViewer.data.clientWidth < lmViewer.data.clientHeight) {
            $(' #seriesList').css('width', $(' #imageContainer').width().toString());
          }

        } catch (err) {
          // 上一段行代码有时出bug，但尚未找到问题所在，先用try catch语句临时顶替下，保证程序能够正常运行
        }
      },

      readjustInstanceWWWL: function (obj) {
        var curDiv = obj.element;
        var curDiv = obj.element;
        var curElement = cornerstone.getEnabledElement(curDiv);

        var curImageIDs = [];

        // find the row and column indexes of current element(from 1 not 0)
        var eleRowIndex = obj.element.id.substring(
          obj.element.id.indexOf('image') + 5,
          obj.element.id.indexOf('image') + 6);
        var eleColumnIndex = obj.element.id.substring(
          obj.element.id.indexOf('image') + 6);
        eleRowIndex = parseInt(eleRowIndex);
        eleColumnIndex = parseInt(eleColumnIndex);

        // the image window number
        var eleIndex = 0;
        if ('' != lmViewer.data.sort && 1 == lmViewer.data.iWindowVNum && 1 == lmViewer.data.iWindowHNum) {
          eleIndex = parseInt(lmViewer.data.sort);
        } else {
          eleIndex = eleRowIndex * lmViewer.data.iWindowVNum + eleColumnIndex;
        }

        // the series number
        var eleImgIndex = 0;
        if (lmViewer.data.iWindowHNum * lmViewer.data.iWindowVNum == 1) {
          eleImgIndex = lmViewer.data.sort;
        } else {
          eleImgIndex = lmViewer.data.loadedIndex[eleIndex] == -1 ? eleIndex : lmViewer.data.loadedIndex[eleIndex];
        }

        var _obj = {
          series: lmViewer.data.seriesArray[eleImgIndex],
          imagesid: curImageIDs
        };
        if (lmViewer.data.getDicomButtonPressed) {
          lmViewer.fn.loadImages(_obj);
        } else {
          lmViewer.fn.loadImages(_obj);
          if (lmViewer.data.globalWW[eleIndex] != undefined && lmViewer.data.globalWL[eleIndex] != undefined) {
            curImageIDs[obj.index] = curImageIDs[obj.index] +
              '&windowWidth=' + lmViewer.data.globalWW[eleIndex].toString() +
              '&windowCenter=' + lmViewer.data.globalWL[eleIndex].toString();
          }
        }

        cornerstone.loadAndCacheImage(curImageIDs[obj.index]).then(function (image) {
          //todo tangzhengxiong 2016/9/18
          lmViewer.ui.hideLoading();
          lmViewer.ui.displayDiv();

          if (lmViewer.data.isDesktop) {
            var _obj = {
              element: undefined,
              image: image
            };
            var imgIndex = lmViewer.fn.getImgIndex(_obj);
            var elementIdx = 0;
            if (lmViewer.data.iWindowHNum * lmViewer.data.iWindowVNum != 1) {
              for (var i = 0; i < lmViewer.data.loadedIndex.length; i++) {
                if (imgIndex.series == lmViewer.data.loadedIndex[i]) {
                  elementIdx = i;
                  break;
                }
              }
              if (i == lmViewer.data.loadedIndex.length) {
                elementIdx = imgIndex.series;
              }
            }
          }

          if (lmViewer.data.isMobile || imgIndex.instance == lmViewer.data.wheelInstanceNum[elementIdx]) {
            cornerstone.displayImage(curDiv, image);
            var viewport = curElement.viewport;

            if (lmViewer.data.getDicomButtonPressed === false) {
              viewport.voi.windowCenter = image.windowCenter;
              viewport.voi.windowWidth = image.windowWidth;
              // if(imageScale[eleRowIndex*iWindowVNum+eleColumnIndex] != undefined){
              // 	viewport.scale = parseFloat(imageScale[eleRowIndex*iWindowVNum+eleColumnIndex]);
              // }
            }

            cornerstone.setViewport(curDiv, viewport);
            if (image.data == undefined) { // JPG
              cornerstoneTools.probe.disable(obj.element);
              cornerstoneTools.rectangleRoi.disable(obj.element);
              cornerstoneTools.ellipticalRoi.disable(obj.element);
              cornerstoneTools.simpleAngle.disable(obj.element);
              cornerstoneTools.lengthTouch.disable(obj.element);
            }
          }
        });
      },

      drawReferenceLine: function (obj) {
        // 切片图行列索引
        var _obj = {
          element: obj.element,
          image: undefined
        };
        var elementIdx = lmViewer.fn.getImgIndex(_obj);
        var eleSeries = elementIdx.series;
        var eleInstance = elementIdx.instance;

        for (var i = 0; i < lmViewer.data.iWindowHNum; i++) {
          for (var j = 0; j < lmViewer.data.iWindowVNum; j++) {
            if (i * lmViewer.data.iWindowVNum + j >= lmViewer.data.loadedIndex.length) {
              break;
            }

            var curElement = $('#image' + i.toString() + j.toString()).get(0);
            var context = cornerstone.getEnabledElement(curElement).canvas.getContext('2d');

            // 定位图行列索引
            _obj.element = curElement;
            var curElementIdx = lmViewer.fn.getImgIndex(_obj);
            var curEleSeries = curElementIdx.series;
            var curEleInstance = curElementIdx.instance;

            /*
             *  以下为自定义算法
             */
            var startX = 0;
            var startY = 0;
            var endX = 0;
            var endY = 0;

            // 定位图参考系
            var eleRCS = lmViewer.data.tagArray[curEleSeries][curEleInstance].frameOfReferenceUID;

            // 切片图参考系
            var curRCS = lmViewer.data.tagArray[eleSeries][eleInstance].frameOfReferenceUID;

            if (eleRCS != curRCS) {
              continue;
            }

            if (obj.element.id === curElement.id) {
              continue;
            }

            // 定位图方向余弦
            var Xx = parseFloat(lmViewer.data.tagArray[curEleSeries][curEleInstance].imageOrientation.split('\\')[0]);
            var Xy = parseFloat(lmViewer.data.tagArray[curEleSeries][curEleInstance].imageOrientation.split('\\')[1]);
            var Xz = parseFloat(lmViewer.data.tagArray[curEleSeries][curEleInstance].imageOrientation.split('\\')[2]);
            var Yx = parseFloat(lmViewer.data.tagArray[curEleSeries][curEleInstance].imageOrientation.split('\\')[3]);
            var Yy = parseFloat(lmViewer.data.tagArray[curEleSeries][curEleInstance].imageOrientation.split('\\')[4]);
            var Yz = parseFloat(lmViewer.data.tagArray[curEleSeries][curEleInstance].imageOrientation.split('\\')[5]);

            // 切片图方向余弦
            var orientXx = parseFloat(lmViewer.data.tagArray[eleSeries][eleInstance].imageOrientation.split('\\')[0]);
            var orientXy = parseFloat(lmViewer.data.tagArray[eleSeries][eleInstance].imageOrientation.split('\\')[1]);
            var orientXz = parseFloat(lmViewer.data.tagArray[eleSeries][eleInstance].imageOrientation.split('\\')[2]);
            var orientYx = parseFloat(lmViewer.data.tagArray[eleSeries][eleInstance].imageOrientation.split('\\')[3]);
            var orientYy = parseFloat(lmViewer.data.tagArray[eleSeries][eleInstance].imageOrientation.split('\\')[4]);
            var orientYz = parseFloat(lmViewer.data.tagArray[eleSeries][eleInstance].imageOrientation.split('\\')[5]);

            // 切片图像素间距
            var rowSpacing = parseFloat(lmViewer.data.tagArray[eleSeries][eleInstance].pixelSpacing.split('\\')[0]);
            var columnSpacing = parseFloat(lmViewer.data.tagArray[eleSeries][eleInstance].pixelSpacing.split('\\')[1]);
            //			  var rowSpacing = cornerstone.getImage(element).rowPixelSpacing;
            //			  var columnSpacing = cornerstone.getImage(element).columnPixelSpacing;

            // 切片图行列
            //			  var row = cornerstone.getImage(element).rows;
            //			  var column = cornerstone.getImage(element).columns;
            var row = parseFloat(lmViewer.data.tagArray[eleSeries][eleInstance].rows);
            var column = parseFloat(lmViewer.data.tagArray[eleSeries][eleInstance].columns);

            // 定位图行列
            var rowDis = parseFloat(lmViewer.data.tagArray[curEleSeries][curEleInstance].rows);
            var columnDis = parseFloat(lmViewer.data.tagArray[curEleSeries][curEleInstance].columns);

            // 定位图像素间距
            var rowSpacingDis = parseFloat(lmViewer.data.tagArray[curEleSeries][curEleInstance].pixelSpacing.split('\\')[0]);
            var columnSpacingDis = parseFloat(lmViewer.data.tagArray[curEleSeries][curEleInstance].pixelSpacing.split('\\')[1]);
            //			  var rowSpacingDis = cornerstone.getImage(curElement).rowPixelSpacing;
            //			  var columnSpacingDis = cornerstone.getImage(curElement).columnPixelSpacing;

            // 定位图位置
            var Dx = parseFloat(lmViewer.data.tagArray[curEleSeries][curEleInstance].imagePosition.split('\\')[0]);
            var Dy = parseFloat(lmViewer.data.tagArray[curEleSeries][curEleInstance].imagePosition.split('\\')[1]);
            var Dz = parseFloat(lmViewer.data.tagArray[curEleSeries][curEleInstance].imagePosition.split('\\')[2]);

            // 定位图法向量
            var Zx = Xy * Yz - Yy * Xz;
            var Zy = Xz * Yx - Yz * Xx;
            var Zz = Xx * Yy - Yx * Xy;

            // 构造定位图空间坐标变换矩阵及其逆阵
            var transferMatrix = [[Xx, Yx, Zx, Dx], [Xy, Yy, Zy, Dy], [Xz, Yz, Zz, Dz], [0, 0, 0, 1]];
            var invTransferMatrix = inverseMatrix(transferMatrix);

            // 切片图四角位置
            var x = parseFloat(lmViewer.data.tagArray[eleSeries][eleInstance].imagePosition.split('\\')[0]);
            var y = parseFloat(lmViewer.data.tagArray[eleSeries][eleInstance].imagePosition.split('\\')[1]);
            var z = parseFloat(lmViewer.data.tagArray[eleSeries][eleInstance].imagePosition.split('\\')[2]);
            var x2 = x + orientXx * columnSpacing * column;
            var y2 = y + orientXy * columnSpacing * column;
            var z2 = z + orientXz * columnSpacing * column;
            var x3 = x2 + orientYx * rowSpacing * row;
            var y3 = y2 + orientYy * rowSpacing * row;
            var z3 = z2 + orientYz * rowSpacing * row;
            var x4 = x + orientYx * rowSpacing * row;
            var y4 = y + orientYy * rowSpacing * row;
            var z4 = z + orientYz * rowSpacing * row;

            // 找交点
            var dv = x * Zx + y * Zy + z * Zz;
            var dv2 = x2 * Zx + y2 * Zy + z2 * Zz;
            var dv3 = x3 * Zx + y3 * Zy + z3 * Zz;
            var dv4 = x4 * Zx + y4 * Zy + z4 * Zz;
            var crossP1x = "";
            var crossP1y = "";
            var crossP1z = "";
            var crossP2x = "";
            var crossP2y = "";
            var crossP2z = "";
            if ((dv > 0 && dv2 < 0) || (dv < 0 && dv2 > 0)) {
              if (crossP1x === "" && crossP1y === "" && crossP1z === "") {
                crossP1x = x + (x2 - x) * Math.abs(dv / (dv - dv2));
                crossP1y = y + (y2 - y) * Math.abs(dv / (dv - dv2));
                crossP1z = z + (z2 - z) * Math.abs(dv / (dv - dv2));
              } else {
                crossP2x = x + (x2 - x) * Math.abs(dv / (dv - dv2));
                crossP2y = y + (y2 - y) * Math.abs(dv / (dv - dv2));
                crossP2z = z + (z2 - z) * Math.abs(dv / (dv - dv2));
              }
            }
            if ((dv2 > 0 && dv3 < 0) || (dv2 < 0 && dv3 > 0)) {
              if (crossP1x === "" && crossP1y === "" && crossP1z === "") {
                crossP1x = x2 + (x3 - x2) * Math.abs(dv2 / (dv2 - dv3));
                crossP1y = y2 + (y3 - y2) * Math.abs(dv2 / (dv2 - dv3));
                crossP1z = z2 + (z3 - z2) * Math.abs(dv2 / (dv2 - dv3));
              } else {
                crossP2x = x2 + (x3 - x2) * Math.abs(dv2 / (dv2 - dv3));
                crossP2y = y2 + (y3 - y2) * Math.abs(dv2 / (dv2 - dv3));
                crossP2z = z2 + (z3 - z2) * Math.abs(dv2 / (dv2 - dv3));
              }
            }
            if ((dv3 > 0 && dv4 < 0) || (dv3 < 0 && dv4 > 0)) {
              if (crossP1x === "" && crossP1y === "" && crossP1z === "") {
                crossP1x = x3 + (x4 - x3) * Math.abs(dv3 / (dv3 - dv4));
                crossP1y = y3 + (y4 - y3) * Math.abs(dv3 / (dv3 - dv4));
                crossP1z = z3 + (z4 - z3) * Math.abs(dv3 / (dv3 - dv4));
              } else {
                crossP2x = x3 + (x4 - x3) * Math.abs(dv3 / (dv3 - dv4));
                crossP2y = y3 + (y4 - y3) * Math.abs(dv3 / (dv3 - dv4));
                crossP2z = z3 + (z4 - z3) * Math.abs(dv3 / (dv3 - dv4));
              }
            }
            if ((dv4 > 0 && dv < 0) || (dv4 < 0 && dv > 0)) {
              if (crossP1x === "" && crossP1y === "" && crossP1z === "") {
                crossP1x = x4 + (x - x4) * Math.abs(dv4 / (dv4 - dv));
                crossP1y = y4 + (y - y4) * Math.abs(dv4 / (dv4 - dv));
                crossP1z = z4 + (z - z4) * Math.abs(dv4 / (dv4 - dv));
              } else {
                crossP2x = x4 + (x - x4) * Math.abs(dv4 / (dv4 - dv));
                crossP2y = y4 + (y - y4) * Math.abs(dv4 / (dv4 - dv));
                crossP2z = z4 + (z - z4) * Math.abs(dv4 / (dv4 - dv));
              }
            }

            // 计算定位图上当前定位线的起点和终点坐标
            var relativeX = invTransferMatrix[0][0] * crossP1x + invTransferMatrix[0][1] * crossP1y + invTransferMatrix[0][2] * crossP1z + invTransferMatrix[0][3] * 1;
            var relativeY = invTransferMatrix[1][0] * crossP1x + invTransferMatrix[1][1] * crossP1y + invTransferMatrix[1][2] * crossP1z + invTransferMatrix[1][3] * 1;
            var relativeXEnd = invTransferMatrix[0][0] * crossP2x + invTransferMatrix[0][1] * crossP2y + invTransferMatrix[0][2] * crossP2z + invTransferMatrix[0][3] * 1;
            var relativeYEnd = invTransferMatrix[1][0] * crossP2x + invTransferMatrix[1][1] * crossP2y + invTransferMatrix[1][2] * crossP2z + invTransferMatrix[1][3] * 1;

            // 如果是JPG格式，校准坐标系
            var rowScale = 1;
            var columnScale = 1;
            if (cornerstone.getImage(curElement).data == undefined) { // JPG
              var jpgRow = cornerstone.getImage(curElement).rows;
              var jpgColumn = cornerstone.getImage(curElement).columns;
              rowScale = rowDis / jpgRow;
              columnScale = columnDis / jpgColumn;
            }
            relativeX = relativeX / (columnSpacingDis);
            relativeY = relativeY / (rowSpacingDis);
            relativeXEnd = relativeXEnd / (columnSpacingDis);
            relativeYEnd = relativeYEnd / (rowSpacingDis);

            startX = relativeX;
            startY = relativeY;
            endX = relativeXEnd;
            endY = relativeYEnd;

            var startCanvasPt = {x: startX, y: startY};
            var endCanvasPt = {x: endX, y: endY};
            var imgOriginPt = cornerstone.pixelToCanvas(curElement, {x: 0, y: 0});
            var startImagePt = cornerstone.pixelToCanvas(curElement, startCanvasPt);
            var endImagePt = cornerstone.pixelToCanvas(curElement, endCanvasPt);

            // 将图像坐标系转换至Canvas坐标系
            startImagePt.x = imgOriginPt.x + (startImagePt.x - imgOriginPt.x) / columnScale;
            startImagePt.y = imgOriginPt.y + (startImagePt.y - imgOriginPt.y) / rowScale;
            endImagePt.x = imgOriginPt.x + (endImagePt.x - imgOriginPt.x) / columnScale;
            endImagePt.y = imgOriginPt.y + (endImagePt.y - imgOriginPt.y) / rowScale;

            // 在每张定位图绘制定位线条
            context.save();
            context.beginPath();
            context.strokeStyle = 'yellow';
            context.lineWidth = 2;

            if (cornerstone.getImage(curElement).data == undefined) { // JPG
              context.moveTo(startImagePt.x, startImagePt.y);
              context.lineTo(endImagePt.x, endImagePt.y);
            } else {// DICOM
              context.moveTo(startCanvasPt.x, startCanvasPt.y);
              context.lineTo(endCanvasPt.x, endCanvasPt.y);
            }

            context.stroke();
            context.restore();
          }
        }
      },
      updateAllImageDisplayed: function () {
        /**
         * version:1.0
         * date:2016-8-12
         * auth:tangzhengxiong
         * desc:更新所有显示的图片
         *
         * */
        for (var i = 0; i < lmViewer.data.iWindowHNum; i++) {
          for (var j = 0; j < lmViewer.data.iWindowVNum; j++) {
            if (i * lmViewer.data.iWindowVNum + j >= lmViewer.data.loadedIndex.length) {
              break;
            }
            var curElement = $('#image' + i.toString() + j.toString()).get(0);
            cornerstone.updateImage(curElement);
          }
        }
      },

      retrieveShare: function () {
        var _params = lmViewer.data.queryParams;
        if (_params.eformid != "null" && _params.eformid != null && _params.eformid != '') {
          var _data = {
            eformid: _params.eformid
          };
          lmViewer.srv.service_eformimage_eformid(_data, function () {
            var result = data.result;
            if (result == 0) {
              var eformInfo = data.message;
              lmViewer.data.curImageID = eformInfo.imageid;

              var _data = {
                imageId: lmViewer.data.curImageID
              };
              // get image information
              lmViewer.srv.service_image_imageId(_data, function (data) {
                var message = data.message;
                /*                                var displayText = '拍摄机构：' + '&nbsp'
                 + message.institutionname + '<br/>'
                 + '患者姓名：' + '&nbsp'
                 + message.patientname;
                 if (message.sex == 0) {
                 displayText += ' ，男';
                 } else {
                 displayText += ' ，女';
                 }
                 displayText += '<br/>';
                 displayText += '拍摄时间：' + '&nbsp'
                 + message.studydate;*/
                lmViewer.data.imageInfo = message;

                lmViewer.data.iWindowVNum = 1;
                lmViewer.data.iWindowHNum = 1;

                lmViewer.data.isloaded = 1;

                lmViewer.fn.retrieveImage();

                // show the content
                var content = document.getElementById("content-forwrap");
                content.style.display = "block";
              }, function (data) {
                humane.log("影像服务器连接错误，请联系客服。");
              });

            }
          }, function (data) {
            humane.log("影像服务器连接错误。Cannot connect server to get the series information.");
          });

          // 否则影像共享通过直接传递的是 imageid 参数查看影像
        } else {
          lmViewer.data.isloaded = 1;
          var data = {
            shareid: lmViewer.data.queryParams.shareid
          };
          lmViewer.srv.service_share2image_shareid(data, function (data) {
//                    console.log("[service_share2image_shareid|success]---"+JSON.stringify(data,null,4));
            var result = data.result;
            if (result == 0) {
              var shareInfo = data.message;
              lmViewer.data.curImageID = shareInfo.imageid;

              // get image information
              var service_image_imageId_data = {
                imageId: 69
              };
              lmViewer.srv.service_image_imageId(service_image_imageId_data, function (data) {
                // console.log("[service_image_imageId|success]---");
                /*                            var endtime = Date.parse(shareInfo.endtime.replace(
                 /-/g, "/")
                 + ' 00:00:00');*/

                var message = data.message;
                lmViewer.data.imageInfo = message;

                lmViewer.data.iWindowVNum = 1;
                lmViewer.data.iWindowHNum = 1;

                /*                            var date = new Date();
                 lmViewer.data.now = date.getFullYear() + "-";
                 lmViewer.data.now = lmViewer.data.now + (date.getMonth() + 1) + "-";
                 lmViewer.data.now = lmViewer.data.now + date.getDate() + " ";
                 lmViewer.data.now = lmViewer.data.now + date.getHours() + ":";
                 lmViewer.data.now = lmViewer.data.now + date.getMinutes() + ":";
                 lmViewer.data.now =lmViewer.data.now + date.getSeconds() + "";

                 var curTime = Date
                 .parse(lmViewer.data.now.replace(/-/g, "/"));

                 if (endtime < curTime) {
                 humane.log("到达分享截至日期，分享已结束");
                 return;
                 }*/
                /*                     if (shareInfo.checkcode == "") {

                 /!*									checkCode(hosturl, curImageID,
                 shareInfo.checkcode);*!/
                 retrieveImage(lmViewer.data.hosturl, lmViewer.data.curImageID);
                 } else {*/
                isloaded = 1;
                lmViewer.fn.retrieveImage();
                // show the content
                var content = document.getElementById("content-forwrap");
                content.style.display = "block";
                // }
              });
            }

          });
        }


      },

      retrieveImage: function () {
        var service_image_imageId_data = {
          imageId: lmViewer.data.curImageID
        };
        lmViewer.srv.service_image_imageId(service_image_imageId_data, function (data) {
          //console.log("[service_image_imageId|success]---");
          var imageInfo = data.message;

          lmViewer.data.queryParams.patId = imageInfo.patientid;
          lmViewer.data.queryParams.studyUID = imageInfo.studyid;

          lmViewer.ctrl.loadStudy();
        });
        /* $.ajax({
         url : hosturl + '/imagecloud/service/image/' + imageid,
         type : 'get',
         dataType : 'json',
         success : function(data) {
         var imageInfo = JSON.parse(data.message);

         patId = imageInfo.patientid;
         studyUID = imageInfo.studyid;

         loadStudy(hosturl, patId, studyUID, dcmurl,serverURL);

         },
         error : function(data) {
         humane
         .log(
         "影像服务器连接错误。Cannot connect server to get the series information.",
         {
         timeout : 1000,
         clickToClose : true,
         addnCls : 'humane-error'
         });
         }
         });*/

      },

    },
    ctrl: {
      /*            init:function(){
       // var _str = "http://123.56.201.253/#/doctorMain/ddetailMessage?patientID=1159&studyUID=1.2.156.112572.18161010101313.5325151913.1241&imageid=74&askId=354&image2askid=386&askType=0&reportFlag=1&type=jpg&a";
       lmViewer.fn.parseQueryString(window.location.href);
       //  lmViewer.fn.parseQueryString(_str);
       },*/
      init: function () {

        // var _str = "http://123.56.201.253/#/doctorMain/ddetailMessage?patientID=1159&studyUID=1.2.156.112572.18161010101313.5325151913.1241&imageid=74&askId=354&image2askid=386&askType=0&reportFlag=1&type=jpg&a";
        lmViewer.fn.parseQueryString();
        //lmViewer.fn.parseQueryString(_str);



        //设置工具栏初始位置
        lmViewer.ui.setToolbarPosition();
        //加载手机初始设置
        if (lmViewer.data.isMobile) {
          lmViewer.ui.loadMobile();
        }

        /*
         * 执行humane.log配置信息
         * */
        lmViewer.fn.notifyConfigure();

        lmViewer.srv.service_ImageViewer_getConfig(function (data) {
          console.log("service_ImageViewer_getConfig|success:"+JSON.stringify(data,null,4));
          var urls = data.message.split(";");

          /*
           * Date:2016-9-12
           * Auth:巫瑜
           * desc:
           * lmViewer.fn.parseQueryString(lmViewer.data.queryString);
           * 解析路径参数
           *
           * */


          lmViewer.fn.parseQueryString(lmViewer.data.queryString);
          lmViewer.data.queryParams.dcmurl = urls[0];
          lmViewer.data.queryParams.serverURL = urls[1];
          var _params = lmViewer.data.queryParams;
          if (_params.patId == null || _params.patId == "" || _params.studyUID == null || _params.studyUID == "" || _params.imageType == null
            || _params.imageType == "") {
            _params.patId = (_params.patId == null || _params.patId == "") ? lmViewer.fn.getParameter(lmViewer.data.queryString, "patientID") : _params.patId;
            _params.studyUID = (_params.studyUID == null || _params.studyUID == "") ? window.localStorage.getItem('studyUID') : _params.studyUID;
            _params.imageType = (_params.imageType == null || _params.imageType == "") ? lmViewer.fn.getParameter(lmViewer.data.queryString, "type") : _params.imageType;
          }


          /*
           * 获取到Tag信息
           *
           * */
          lmViewer.fn.loadTagInfos();

          /*                    // 判断是否显示相关的Tab
           if (null == lmViewer.data.queryParams.image2askid || '' == lmViewer.data.queryParams.image2askid || 'null' == lmViewer.data.queryParams.image2askid) {
           //表示是阅片的状态
           $("#liTabReport").css("display", "none");
           $("#liTabInfo").css("display", "none");
           $("#liTabSReport").css("display", "none");
           }
           else {
           //表示是咨询的状态
           $("#liTabStartConsult").css("display", "none");
           }*/

          /*            lmViewer.data.queryParams.askId = getParameter(lmViewer.data.queryString, "askid" );
           lmViewer.data.queryParams.imageId = getParameter(lmViewer.data.queryString, "imageid" );*/

          lmViewer.data.totalSeries = 0;
          if (lmViewer.data.isDesktop === true) {
            $('#enableScrollStack').css('display', 'none');
          }
          lmViewer.ui.cancelBindKey();
          lmViewer.ui.loadButtonHint();
          //分享阅片

          if (_params.shareid != null || _params.eformid != null) {
            //默认为jpg图像，
            _params.imageType = 'jpg';
            lmViewer.fn.retrieveShare();
            // show the content
            /*                        var content = document.getElementById("content-forwrap");
             content.style.display = "block";*/
          } else {
            //我的影像
            lmViewer.fn.getStudyNumber();

            var _data = {
              imageId:lmViewer.data.queryParams.imageId
              // imageId: 14
            }
            lmViewer.srv.service_image_imageId(_data, function (data) {
              // console.log('service_image_imageId | success....');
              var message = data.message;
              lmViewer.data.imageInfo = message;

              lmViewer.data.iWindowVNum = 1;
              lmViewer.data.iWindowHNum = 1;
              /*                            var _data = {
               add:"eee"
               }*/
              lmViewer.ctrl.loadStudy();
              window.addEventListener('resize', lmViewer.ui.resizeCanvas, false);
              if (_params.imageType == 'jpg') {
                $('#getDicom').find('span').html('DCM');
              } else {
                $('#getDicom').find('span').html('JPG');
              }
            });
          }

        });
      },

      loadStudy: function () {
        var _params = lmViewer.data.queryParams;
        var _data = {
          patientid: _params.patId,
          studyid: _params.studyUID,
          dcmURL: _params.dcmurl
        };
        lmViewer.srv.service_series_getseries(_data, function (data) {
                  console.log("[imageShow|service_series_getseries|success]---"+JSON.stringify(data,null,4));
          var _message = data.message;
          lmViewer.data.iSeriesNum = _message.length;
          lmViewer.data.changgeSeriesByIndex = 0;
          for (var i = 0; i < lmViewer.data.iSeriesNum; i++) {
            lmViewer.data.tagArray[i] = new Array();
          }

          if (lmViewer.data.iSeriesNum > 0)
          {
          // console.log('after');
            lmViewer.data.series = _message;
            //todo tangzhengxiong 2016/9/19
            lmViewer.data.curSeriesId = lmViewer.data.series[0].seriesIUID;
            //todo tangzhengxiong 2016/9/26
            lmViewer.data.currentStatus.series = lmViewer.data.series[0];
            // console.log(lmViewer.data.series);
            lmViewer.data.flag=true;

            lmViewer.data.totalSeries = lmViewer.data.iSeriesNum;

            for (var i = 0; i < lmViewer.data.iSeriesNum; i++) {
              // 取序列下的影像
              var _obj = {
                seriesUID: lmViewer.data.series[i].seriesIUID,
                index: i
              };

              lmViewer.fn.loadInstances(_obj);
            }
          } else {
            humane.log("影像服务器连接错误。Cannot connect server to get the study.");
          }
        });
      },

      initDicomViewer: function () {

        // 准备显示
        !function ($) {
          // is loaded completely
          var itotal = 0;
          for (var i = 0; i < lmViewer.data.seriesArray.length; i++) {
            itotal = itotal + lmViewer.data.loaded[i];

          }
          if (itotal != lmViewer.data.totalSeries) {
            return;
          }

          // 对序列排序
          lmViewer.fn.sortSeries();
          //todo 调试先去掉 2016-9-13 巫瑜
          // hide the buttons displayed in vertical line on the left side when the images modality is not CT
          // if(lmViewer.data.series[0].modality != "CT" || lmViewer.data.isMobile){
          //     lmViewer.ui.hideButtons();
          // }
          // get the global variable "maxSeriesNum"
          lmViewer.data.maxSeriesNum = lmViewer.data.seriesArray[0].instance.length;
          for (var i = 0; i < lmViewer.data.iSeriesNum; i++) {
            lmViewer.data.maxSeriesNum = lmViewer.data.maxSeriesNum > lmViewer.data.seriesArray[i].instance.length
              ? lmViewer.data.maxSeriesNum : lmViewer.data.seriesArray[i].instance.length;
          }

          // display div
          lmViewer.ui.hideLoading();

          lmViewer.ui.displayDiv();
          // sort the "tags" array, in order to unify the structure
          // of "tagArray" and "seriesArray" ----------------------------------Updated by TanQilu
          lmViewer.fn.sortTags();
          // distinguish into groups
          lmViewer.fn.distinguishGroup();
          //renumber the instances of every series -----------------------------------Updated by TanQilu
          lmViewer.fn.renumberInstances();
          //todo 不显示左边系列列表 巫瑜 2016-9-13
          // 取序列列表（显示tab1）
          //lmViewer.ui.generateSeriesList();
          // 设置进度条 显示影像
          lmViewer.ui.showSeries();

        }(jQuery);
      },

      showSeriesByIndex: function (index) {
        lmViewer.ui.hideDiv();
        lmViewer.ui.showLoading();

        lmViewer.data.isShowSeriesByIndexPressed = true;
        cornerstone.imageCache.purgeCache();
        lmViewer.data.changgeSeriesByIndex = index;

        if (index === lmViewer.data.clickedSeries) {
          return;
        }

        lmViewer.data.clickedSeries = index;
        if (1 != lmViewer.data.iWindowVNum * lmViewer.data.iWindowHNum) {
          return;
        }

        lmViewer.data.wheelInstanceNum[0] = 0;
        lmViewer.data.sort = index;
        //todo tangzhengxiong 2016/9/18
       // lmViewer.data.curSeriesId = lmViewer.data.series[index].seriesUID;
        //todo tangzhengxiong 2016/9/26
        lmViewer.data.currentStatus.series = lmViewer.data.series[index];
        lmViewer.data.currentStatus.instance = lmViewer.data.seriesArray[index].instance[0];
        lmViewer.fn.RT.setCurrentTag();


        lmViewer.ui.cancelBindKey();
        lmViewer.ui.loadButtonHint();

        lmViewer.data.groupIndex[0] = lmViewer.data.groupIndex[lmViewer.data.clickedSeries];

        lmViewer.ui.resetImageContainer();
        lmViewer.ui.showSeries();
      },

      // initImageList: function (data,success) {
      //   var _data=data;
      //   lmViewer.srv.getImageList(_data, success)
      // }


    },
    ui: {},
    srv: {},
    RT:{}
  };
}
